package com.pcy.codegenerator.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Component
public class BrowserCommandRunner implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(BrowserCommandRunner.class);
    @Value("${app.openurl}")
    private String openurl;

    @Value("${app.browser-path}")
    private String defaultBrowserPath;

    @Value("${app.open-browser}")
    private boolean isOpen;
    private static String googlePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
    private static String edgePath = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe";
    private static String  iepath = "C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe";

    @Override
    public void run(String... args){
        //打开谷歌浏览器，打开失败再打开ie
        if(isOpen){
            runexe(openurl,defaultBrowserPath,edgePath,googlePath,iepath);
        }
    }


    public static void runexe(String openurl,String... paths){
        for(String path : paths){
            try {
                if(!StringUtils.isEmpty(path)){
                    Runtime run = Runtime.getRuntime();
                    run.exec(path + " " + openurl);
                    logger.debug("启动浏览器打开项目成功");
                    break;
                }
            } catch (IOException e) {
                logger.error("打开浏览器错误",e);
            }
        }

    }
}